// 路由权限控制
// 参考 ruoyi-ui 的实现，适配 uni-app

import userStore from '@/store/user.js';

// 白名单页面（不需要登录）
const whiteList = [
  '/pages/login',
  '/pages/register'
];

// 检查是否需要登录
const needAuth = (path) => {
  return !whiteList.includes(path);
};

// 检查登录状态 - 直接检查本地存储，不依赖可能有问题的store
export const checkAuth = () => {
  console.log('checkAuth: Starting authentication check');
  try {
    // 尝试使用store
    const storeResult = userStore.getters['user/isLoggedIn'];
    console.log('checkAuth: Store result:', storeResult);
    if (storeResult !== undefined) {
      console.log('checkAuth: Using store result, returning:', storeResult);
      return storeResult;
    }
  } catch (error) {
    console.log('checkAuth: Store access error:', error);
  }
  
  // 回退到本地存储检查
  const token = uni.getStorageSync('token');
  console.log('checkAuth: Token from storage:', token);
  const result = !!token;
  console.log('checkAuth: Final result:', result);
  return result;
};

// 路由守卫
export const routeGuard = (to, from, next) => {
  const path = to.path;
  console.log('RouteGuard: Checking path:', path);
  console.log('RouteGuard: Full to object:', to);
  
  // 检查是否需要登录
  if (needAuth(path)) {
    console.log('RouteGuard: Path needs authentication');
    // 需要登录，检查是否已登录
    if (checkAuth()) {
      console.log('RouteGuard: User is authenticated, allowing access');
      // 已登录，允许访问 - 在uni-app拦截器中返回true
      return true;
    } else {
      console.log('RouteGuard: User not authenticated, redirecting to login');
      // 未登录，跳转到登录页
      uni.reLaunch({
        url: '/pages/login'
      });
      return false;
    }
  } else {
    console.log('RouteGuard: Path does not need authentication, allowing access');
    // 不需要登录，允许访问
    return true;
  }
};

// 检查特定权限
export const checkPermission = (permission) => {
  const permissions = userStore.getters['user/permissions'];
  return permissions.includes(permission);
};

// 检查特定角色
export const checkRole = (role) => {
  const roles = userStore.getters['user/roles'];
  return roles.includes(role);
};

// 自动登录检查
export const autoLoginCheck = () => {
  if (checkAuth()) {
    // 已登录，检查 token 是否有效
    // 这里可以添加 token 有效性检查逻辑
    return true;
  }
  return false;
};

// 强制登出
export const forceLogout = () => {
  userStore.dispatch('user/clearUser');
  uni.reLaunch({
    url: '/pages/login'
  });
};

// 页面权限检查装饰器
export const requireAuth = (pageConfig) => {
  const originalOnLoad = pageConfig.onLoad;
  
  pageConfig.onLoad = function(options) {
    // 检查登录状态
    if (!checkAuth()) {
      uni.reLaunch({
        url: '/pages/login'
      });
      return;
    }
    
    // 调用原始的 onLoad
    if (originalOnLoad) {
      originalOnLoad.call(this, options);
    }
  };
  
  return pageConfig;
};

// 权限检查装饰器
export const requirePermission = (permission) => {
  return (pageConfig) => {
    const originalOnLoad = pageConfig.onLoad;
    
    pageConfig.onLoad = function(options) {
      // 检查权限
      if (!checkPermission(permission)) {
        uni.showToast({
          title: '没有权限访问此页面',
          icon: 'none'
        });
        uni.navigateBack();
        return;
      }
      
      // 调用原始的 onLoad
      if (originalOnLoad) {
        originalOnLoad.call(this, options);
      }
    };
    
    return pageConfig;
  };
};
